package com.zb.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.zb.bean.Article;
import com.zb.bean.User;
import com.zb.bean.UserRoleRef;
import com.zb.enums.Enums;
import com.zb.qo.ArticleQo;
import com.zb.qo.RegisterQo;
import com.zb.service.ArticleService;
import com.zb.service.UserRoleService;
import com.zb.service.UserService;
import com.zb.util.CryptoUtils;
import com.zb.util.LoggerUtil;
import com.zb.util.web.HttpMethod;
import com.zb.util.web.HttpUtils;
import com.zb.vo.PageVo;

public class AfterQQLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AfterQQLoginServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
    @SuppressWarnings("deprecation")
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginUserName = null;
        String loginUserPwd = null;
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

            String accessToken = null, openID = null, nickName = null;
            if (accessTokenObj.getAccessToken().equals("")) {
                //我们的网站被CSRF攻击了或者用户取消了授权
                //做一些数据统计工作
                //System.out.print("没有获取到响应参数");
                request.setAttribute("loginErrorMsg", "QQ快捷登陆失败");
                request.getRequestDispatcher("/toLogin").forward(request, response);
                return;
            } else {
                accessToken = accessTokenObj.getAccessToken();

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                if (userInfoBean.getRet() == 0) {
                    nickName = userInfoBean.getNickname();
                    //out.println(userInfoBean.getGender() + "<br/>");
                    //out.println("黄钻等级： " + userInfoBean.getLevel() + "<br/>");
                    //out.println("会员 : " + userInfoBean.isVip() + "<br/>");
                    //out.println("黄钻会员： " + userInfoBean.isYellowYearVip() + "<br/>");
                    //out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL30() + "/><br/>");
                    //out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL50() + "/><br/>");
                    //out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL100() + "/><br/>");
                } else {
                    request.setAttribute("loginErrorMsg", "QQ快捷登陆失败");
                    request.getRequestDispatcher("/toLogin").forward(request, response);
                    return;
                }
                
                ServletContext servletContext = this.getServletContext();  
                WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
                UserService userService = (UserService) context.getBean("userServiceImpl"); 
                
                //检查该QQ是否已经注册登录过
                User userObj = userService.getUserByOpenId(openID);
                if(userObj == null){
                    //注册
                    RegisterQo qo = new RegisterQo();
                    qo.setOpenId(openID);
                    qo.setPassword("123456");
                    //qo.setPasswordOk(CryptoUtils.encodeMD5("123456"));
                    qo.setUserName(nickName);
                    userService.register(qo.buildUserInfo());
                    
                    //注册成功后，默认为用户设置user角色
                    UserRoleService userRoleService = (UserRoleService)context.getBean("userRoleServiceImpl");
                    User user = userService.getUserByName(qo.getUserName());
                    UserRoleRef ur = new UserRoleRef();
                    ur.setUserId(user.getId());
                    ur.setRoleId(Enums.Role.USER.getId());
                    userRoleService.addUserRole(ur);
                    
                    loginUserName = nickName;
                    loginUserPwd = CryptoUtils.encodeMD5("123456");//默认登陆密码123456
                }else{//已经注册登陆过
                    System.out.println("yes reg");
                    loginUserName = userObj.getUserName();
                    loginUserPwd = userObj.getPassword();
                }
                
                UsernamePasswordToken token = new UsernamePasswordToken();  
                token.setUsername(loginUserName);  
                token.setPassword(loginUserPwd.toCharArray());  
                SecurityUtils.getSubject().login(token);
                LoggerUtil.LoggerFormatPattern("用户：{0} 登录成功", userInfoBean.getNickname());
                SecurityUtils.getSubject().getSession().setTimeout(1000 * 60 * 60);
                
                request.getSession().setAttribute("nickName", userInfoBean.getNickname());
                request.getSession().setAttribute("logoImg", userInfoBean.getAvatar().getAvatarURL30());
                //mav.addObject("nickName", loginUserName);
                //mav.addObject("logoImg", userInfoBean.getAvatar().getAvatarURL30());
                
                //QQ名称也许会被用户修改，所以需要更新一下数据库
                //userObj = userService.getUserByOpenId(openID);
                userObj.setUserName(userInfoBean.getNickname());
                userObj.setUpdateTime(new Date());
                userService.updateUser(userObj);
                
                PageVo<Article> articleList = null;
                try {
                    ArticleService articleService = (ArticleService)context.getBean("articleServiceImpl");
                    articleList = articleService.getArticleList(new ArticleQo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                User userInfo = null;
                try {
                    userInfo = userService.getUserByName(userInfoBean.getNickname());
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                String url = "http://api.uyan.cc?mode=des&uid=" + userInfo.getId() 
                        + "&uname=" + URLEncoder.encode(userInfo.getUserName(),"UTF-8") 
                        + "&email=" + URLEncoder.encode(userInfo.getEmail() == null ? "" : userInfo.getEmail(),"UTF-8") 
                        + "&uface=" + URLEncoder.encode(userInfoBean.getAvatar().getAvatarURL30() == null ? "" : userInfoBean.getAvatar().getAvatarURL30(),"UTF-8") 
                        + "&ulink=&expire=3600&key=" + URLEncoder.encode("gnabuohz58","UTF-8");
                String desstr = null;
                try {
                    desstr = HttpUtils.getString(url, HttpMethod.GET);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Cookie cookie = new Cookie("syncuyan", desstr);
                cookie.setPath("/");
                cookie.setMaxAge(3600);
                cookie.setDomain("www.2b2b92b.com");
                response.addCookie(cookie);
                
                request.setAttribute("articleList", articleList);
                request.getRequestDispatcher("/index/index").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("loginErrorMsg", "QQ快捷登陆失败");
            request.getRequestDispatcher("/toLogin").forward(request, response);
        }
    }
    
}
